for: Repeats an action over a series of itemswhile: Repeats an action until a given condition is satisfiedfor loopfor repeats an action for every element in an object>>> for character in 'Kyle':
... print("Give me a " + character + "!")
...
Give me a K!
Give me a y!
Give me a l!
Give me a e!for worksSo what is going on here?
for loop looks at what it will iterate through - in this case it is a string, KyleKyle, as character.print function for each character in Kyle successivelySo the for loop is equivalent to:
print("Give me a K!")
print("Give me a y!")
print("Give me a l!")
print("Give me a e!")while loopwhile repeats an action until a given condition is satisfiedIn [1]: i = 5
...:
...: while i > 0:
...: print(str(i) + "...")
...: i = i - 1
...:
...: print("Blast-off!")
5...
4...
3...
2...
1...
Blast-off!while worksi, that we set to 5 before running the loopi is greater than 0, we tell Python to evaluate the print function1 from ii is equal to 0, we exit the loop and print "Blast-off" to the consoleBeware of the infinite while loop!
if, elif, and else< Less than> Greater than<= Less than or equal to>= Greater than or equal to== Is equal to!= Is not equal toTrue and Falseand, or, & not>>> mylist = [2, 4, 6, 8, 10, 12]
>>> for number in mylist:
... if number > 7:
... print(str(number) + " is greater than 7!")
... else:
... print(str(number) + " is less than 7!")
...
2 is less than 7!
4 is less than 7!
6 is less than 7!
8 is greater than 7!
10 is greater than 7!
12 is greater than 7!def is_even(x):
if x % 2 == 0:
return(True)
else:
return(False)
>>> is_even(8)
True
>>> is_even(99)
Falseclass Employee:
company = "TCU"
def __init__(self, name, salary):
self.name = name
self.salary = salary
# Let's create a class instance
doug = Employee(name = "Doug", salary = 50000)
doug.company
'TCU' # the result
def get_raise(self, raise_amount):
self.salary = self.salary + raise_amount
doug.get_raise(5000)